package com.woniu.controller;

import com.woniu.entity.Result;
import com.woniu.entity.dto.UserLoginDTO;
import com.woniu.entity.vo.RouterVo;
import com.woniu.interceptor.AuthenticationContextHolder;
import com.woniu.pojo.Menu;
import com.woniu.pojo.User;
import com.woniu.service.IMenuService;
import com.woniu.service.IUserService;
import com.woniu.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录，注销，获取登录的账户信息，获取动态路由
 */
@RestController
@RequestMapping("/system")
@Schema(title = "登录注销相关")
@Slf4j
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    @Schema(title = "登录")
    public Result<Map<String, Object>> login(@Valid @RequestBody UserLoginDTO userLoginDTO) {
        // 调用service进行登录操作
        User user = userService.login(userLoginDTO);
        // 判断登录的结果
        if (user == null) {
            return Result.error("用户名或者密码错误");
        }

        //token令牌。证明用户已经登录
        //调用jwt的工具类，生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("mobile", user.getMobile());
        String jwtToken = JwtUtil.createJWT(user.getId(), map, 1000L * 60 * 60 * 24);

        //将生成的token保存到redis中
        stringRedisTemplate.opsForValue().set("token-" + user.getUsername(), jwtToken,30, TimeUnit.MINUTES);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", jwtToken);
        return Result.ok(resultMap);
    }

    @GetMapping("/info")
    @Schema(title = "获取登录的用户信息")
    public Result<Map<String, Object>> info(HttpServletRequest request) throws Exception {
//       //1.从请求头中获取token
//        String authorization  = request.getHeader("Authorization");
//        if (!StringUtils.hasLength(authorization)) {
//            return Result.error("用户未登录");
//        }
//        String jwtToken = authorization.substring(7);
//        //解析jwtToken 获取载荷中的用户名
//        Claims claims = JwtUtil.parseJWT(jwtToken);
//        String username=claims.get("username").toString();
//        //2.根据token获取用户信息
//        User user = userService.getByUsername(username);


        //1.从请求头中获取token
        String username= AuthenticationContextHolder.getContext();

        //2.根据token查询用户信息
        User user =userService.getByUsername(username);

        //3.根据token获取角色信息
        List<String> roles = new ArrayList<>();
        roles.add("admin");
        //4.根据token获取权限信息
        List<String> permissions = new ArrayList<>();
        permissions.add("*:*:*");
        //5.返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("roles", roles);
        map.put("permissions", permissions);
        map.put("user", user);
        return Result.ok(map);
    }

    @Schema(title = "获取菜单集合")
    @GetMapping("/router")
    public Result<List<RouterVo>> listRouterMenus(HttpServletRequest request) throws Exception {
//        String token = request.getHeader("Authorization");
//        if (StringUtils.isEmpty(token) || !token.startsWith("Bearer ")) {
//            return Result.error("非法的token");
//        }
//        String jwtToken = token.substring(7);
//        // 解析jwtToken, 获取载荷中的用户名
//        Claims claims = JwtUtil.parseJWT(jwtToken);
//        String username = claims.get("username").toString();

        String username = AuthenticationContextHolder.getContext();

        // 根据用户名获取该用户具备的权限菜单列表
        List<Menu> menus = menuService.listTreeMenusByUsername(username);
        List<RouterVo> routerVos = menuService.buildMenus(menus);
        return Result.ok(routerVos);
    }

    @PostMapping("/logout")
    @Schema(title = "注销")
    public Result logout(HttpServletRequest request) {
        //1.从请求头中获取token
//        String authorization  = request.getHeader("Authorization");
//        if (!StringUtils.hasLength(authorization)) {
//            return Result.error("用户未登录");
//        }
//        String jwtToken = authorization.substring(7);
//        //解析jwtToken 获取载荷中的用户名
//        Claims claims = JwtUtil.parseJWT(jwtToken);
//        String username=claims.get("username").toString();
//        String username = AuthenticationContextHolder.getContext();
//        //2.删除redis中的token
//        stringRedisTemplate.delete("token-" + username);
        return Result.ok("注销成功");
    }
}